package com.shimao.celnet.payment.shiro;


import com.shimao.celnet.payment.form.ASysPermissionForm;
import com.shimao.celnet.payment.model.ASysUser;
import com.shimao.celnet.payment.service.ASysPermissionService;
import com.shimao.celnet.payment.service.ASysRoleService;
import com.shimao.celnet.payment.service.ASysUserService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by christ on 2017/4/21.
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private ASysUserService aSysUserService;

    @Autowired
    private ASysPermissionService aSysPermissionService;

    @Autowired
    private ASysRoleService aSysRoleService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限认证方法：MyShiroRealm.doGetAuthorizationInfo()");
        //获取用户名
        ASysUser user = (ASysUser) SecurityUtils.getSubject().getPrincipal();
        String userGuid = user.getGuid();
       //根据用户guid获取用户所拥有的权限
     //   List<ASysPermission> resourcesList = aSysPermissionService.getUserPermission(user.getGuid());
        List<ASysPermissionForm> resourcesList = aSysPermissionService.getAllRolesPermission(userGuid);
        // 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> permissionStr = new HashSet<String>();
        Set<String> roles = new HashSet<String>();
        for(ASysPermissionForm resources: resourcesList){
            //使用set防止重复
            permissionStr.add(resources.getUrl());
            roles.add(resources.getRoleName());
        }
        info.addRoles(roles);
        info.addStringPermissions(permissionStr);
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    // 获取用户的输入的账号. String username = (String)token.getPrincipal();
        ASysUser user = aSysUserService.getByUsername((String)token.getPrincipal());
        if(user==null) throw new UnknownAccountException();
        if (FinalUtil.DISABLE==user.getDeleteFlg()) {
            throw new LockedAccountException(); // 帐号锁定
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getUserName()),
                getName()  //realm name
        );
        // 当验证都通过后，把用户信息放在session里
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("userSessionId", user.getGuid());
        session.setAttribute("userSession", user);
        return authenticationInfo;
    }

    /**
     * 指定principalCollection 清除
     */
  /*  public void clearCachedAuthorizationInfo(PrincipalCollection principalCollection) {

        SimplePrincipalCollection principals = new SimplePrincipalCollection(
                principalCollection, getName());
        super.clearCachedAuthorizationInfo(principals);
    }
*/
}
